package controller.user;

import java.io.PrintWriter;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import base.entity.Page;
import entity.user.User;
import log.annotation.ControllerAnnotation;
import service.user.IUserService;
import util.MYUtil;

@Controller
@RequestMapping("/user")
public class UserController {

	@Resource
	private IUserService userServiceImpl;

	@SuppressWarnings("unchecked")
	@RequestMapping("/permission/addUser")
	@ControllerAnnotation(app = "蚂蚁", classname = "controller.user.UserController", function = "用户管理", methodname = "addUser", model = "用户CRUD", opercation = "增加用户", isMenu = false, menuName = "")
	public void addUser(PrintWriter out, HttpServletRequest request, User user) {
		JSONObject data = new JSONObject();
		user.setPassword(MYUtil.Md5Str(user.getPassword()));
		try {
			userServiceImpl.addSingleUser(user);
			data.put("flag", true);
		} catch (Exception e) {
			data.put("flag", false);
			data.put("msg", "服务器异常");
			e.printStackTrace();
		}
		out.write(data.toJSONString());
	}
	
	@RequestMapping("/updateUserAttachment")
	@ControllerAnnotation(app = "蚂蚁", classname = "controller.user.UserController", function = "用户管理", methodname = "updateUserAttachment", model = "用户CRUD", opercation = "修改用户附件", isMenu = false, menuName = "")
	public void updateUserAttachment(PrintWriter out, HttpServletRequest request, String fileId,String name) {
		User user = (User) MYUtil.getMySession().getAttribute("user");
		try {
			userServiceImpl.updateUserAttachment(user,fileId,name);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 加载所有用户
	 * 
	 * @param out
	 * @param request
	 * @param pageNo
	 * @param pageSize
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/getUsersByPageAndSize")
	@ControllerAnnotation(app = "蚂蚁", classname = "controller.user.UserController", function = "用户管理", methodname = "getUsersByPageAndSize", model = "用户CRUD", opercation = "分页加载用户数据", isMenu = false, menuName = "")
	public void getUsersByPageAndSize(PrintWriter out, HttpServletRequest request, Integer page, Integer rows) {
		JSONObject data = new JSONObject();
		try {
			JSONArray datas = new JSONArray();
			Page<User> p = userServiceImpl.getUsersByPageAndSize(page, rows);
			List<User> users = p.getDatas();
			for (User u : users) {
				JSONObject role = new JSONObject();
				role.put("id", u.getId());
				role.put("account", u.getAccount());
				role.put("name", u.getName());
				role.put("phone", u.getPhone());
				datas.add(role);
			}
			data.put("total", p.getTotalRow());
			data.put("rows", datas);
		} catch (Exception e) {
			e.printStackTrace();
		}
		out.write(data.toJSONString());
	}
}
